﻿using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace vDisk.WindowsPhone
{
    public class Utils
    {
        #region 获取时间戳
        public static string GetTime()
        {
            DateTime timeStamp = new DateTime(1970, 1, 1);  //得到1970年的时间戳
            return ((DateTime.UtcNow.Ticks - timeStamp.Ticks) / 10000000).ToString() ;  //注意这里有时区问题，用now就要减掉8个小时
        }
        #endregion

        #region 根据时间戳获取时间
        public static DateTime GetTime(string times)
        {
            DateTime dtStart = new DateTime(1970, 1, 1);
            long lTime = long.Parse(times + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        #endregion

        #region 获取签名
        public static string GetSignature(string text,string key)
        {
            var hmacsha256 = new HMACSHA256(GetBytes(key));
            var hashmessage = hmacsha256.ComputeHash(GetBytes(text));
            return ByteToString(hashmessage).ToLower();
        }

        static byte[] GetBytes(string text)
        {
            UTF8Encoding encoding = new UTF8Encoding();
            return encoding.GetBytes(text);
        }

        public static string ByteToString(byte[] buff)
        {
            string sbinary = "";

            for (int i = 0; i < buff.Length; i++)
            {
                sbinary += buff[i].ToString("X2"); // hex format
            }
            return (sbinary);
        }
        #endregion

    }
}
